<template>
    <div style="width:100%;height:100%">
        <div class="login-container">
            <div class="title-container">
                <h3 class="title">兰亭书法</h3>
            </div>
            <div class="loginType">
                <div class="accountLogin" :class="{loginTypeSelected:loginType==1}" @click="loginType=1">登录</div>
                <div class="verifyCodeLogin" :class="{loginTypeSelected:loginType==2}" @click="loginType=2">注册</div>
            </div>
            <!-- 登录 -->
            <el-form
                ref="loginFormRef"
                :model="loginForm"
                :rules="loginRules"
                class="login-form"
                autocomplete="on"
                label-position="left"
                v-show="loginType==1"
            >
                <el-form-item prop="userName">
                    <span class="svg-container">
                        <!-- <i class="el-icon-s-custom"></i> -->
                        <UserFilled style="width: 1em; height: 1em; margin-right: 8px"></UserFilled>
                    </span>
                    <el-input
                        ref="userName"
                        v-model="loginForm.userName"
                        placeholder="请输入用户名"
                        name="username"
                        type="text"
                        tabindex="1"
                        autocomplete="on"
                    />
                </el-form-item>
                    <el-form-item prop="password">
                        <span class="svg-container">
                            <!-- <i class="el-icon-lock"></i> -->
                            <Lock style="width: 1em; height: 1em; margin-right: 8px"></Lock>
                        </span>
                        <el-input
                            :key="passwordType"
                            ref="password"
                            v-model="loginForm.password"
                            :type="passwordType"
                            placeholder="请输入密码"
                            name="password"
                            tabindex="2"
                            autocomplete="on"
                            @keyup="checkCapslock"
                            @keyup.enter="handleLogin"
                        />
                        <span class="show-pwd" @click="showPwd">
                            <i
                                :class="
                                    passwordType !== 'password'
                                        ? 'iconfont icon-yanjing'
                                        : 'iconfont icon-yanjing1'
                                "
                            />
                        </span>
                    </el-form-item>
                <el-button
                    :loading="loading"
                    type="primary"
                    style="width: 100%; margin-bottom: 15px; height: 40px !important;"
                    @click.prevent="handleLogin"
                >Login</el-button
                >
                <div style="position: relative">
                </div>
                <!-- <div class="forget" @click="forgetPassword">
                    忘记密码?
                </div> -->
            </el-form>
            <!-- 注册 -->
            <el-form
                ref="verifyCodeLoginFormRef"
                :model="verifyCodeLoginForm"
                :rules="shortMessageLoginRules"
                class="login-form"
                autocomplete="on"
                label-position="left"
                v-show="loginType==2"
            >
                <el-form-item prop="userName">
                    <span class="svg-container">
                        <!-- <i class="el-icon-s-custom"></i> -->
                        <UserFilled style="width: 1em; height: 1em; margin-right: 8px"></UserFilled>
                    </span>
                    <el-input
                        ref="userName"
                        v-model="verifyCodeLoginForm.userName"
                        placeholder="请输入注册的账号名"
                        name="username"
                        type="text"
                        tabindex="1"
                        autocomplete="on"
                    />
                </el-form-item>
                    <el-form-item prop="messageCode">
                        <span class="svg-container">
                            <!-- <i class="el-icon-chat-dot-square"></i> -->
                            <Lock style="width: 1em; height: 1em; margin-right: 8px"></Lock>
                        </span>
                        <el-input
                            ref="messageCode"
                            v-model="verifyCodeLoginForm.messageCode"
                            placeholder="请输入注册的密码"
                            type="password"
                            name="messageCode"
                            tabindex="2"
                        />
                    </el-form-item>
                <el-button
                    :loading="loading2"
                    type="primary"
                    style="width: 100%; margin-bottom: 15px; height: 40px !important;"
                    @click.prevent="handleMessageLogin"
                >Register</el-button
                >

                <div style="position: relative">
                </div>
            </el-form>
        </div>
        <!-- <forget-dialog :forgetDialog="forgetDialog" @forgetClose="closeDialog"></forget-dialog> -->
    </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import Message from '@/components/library/Message'
import { Encrypt } from '@/utils/scret'
import { validUsername } from '@/utils/validate'
// import { createNamespacedHelpers } from 'vuex'
// import forgetDialog from './components/forgetDialog.vue'
// import md5 from 'js-md5'
// const { mapActions, mapMutations } = createNamespacedHelpers('user')
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { addUser, userAccountLogin } from '@/api/user'
// import { setToken } from '@/utils/auth'
export default {
  name: 'lt-login',
  // components: { forgetDialog },
  setup () {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不少于6位数'))
      } else {
        callback()
      }
    }
    const validateMessageCode = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不少于6位数'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const loginForm = reactive({
      userName: '',
      password: ''
    })
    const loginFormRef = ref(null)
    const loginRules = {
      userName: [
        { required: true, trigger: 'blur', validator: validateUsername }
      ],
      password: [
        { required: true, trigger: 'blur', validator: validatePassword }
      ]
    }
    const shortMessageLoginRules = {
      userName: [
        { required: true, trigger: 'blur', validator: validatePhone }
      ],
      messageCode: [
        { required: true, trigger: 'blur', validator: validateMessageCode }
      ]
    }
    const passwordType = 'password'
    let loading = false
    let loading2 = false
    const showDialog = false
    const redirect = 'main'
    const otherQuery = {}
    const validateimg = ''
    const loginType = ref(1) // 登录类型 1：账号登录 2：验证码登录
    const verifyCodeLoginForm = reactive({
      userName: '',
      messageCode: ''
    })
    const verifyCodeLoginFormRef = ref(null)
    const verification = true // 通过v-show控制显示获取还是倒计时
    const timer = 60 // 定义初始时间为60s
    const forgetDialog = false
    const loadingMessage = false // 点击发送验证码后的loading状态
    const store = useStore()
    const router = useRouter()
    const profile = computed(() => {
      return store.state.user.profile
    })
    onMounted(() => {
    //   this.freshValidate()
      // window.addEventListener('storage', this.afterQRScan)
      if (loginForm.username === '') {
        this.$refs.username.focus()
      } else if (loginForm.password === '') {
      // this.$refs.password.focus()
      }
    // this.timer = sessionStorage.getItem("timer");
    })

    function checkCapslock (e) {
    //   const { key } = e
    //   this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z'
    }
    function showPwd () {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    }
    // 登录
    function handleLogin () {
      loginFormRef.value.validate((valid) => {
        console.log(valid)
        if (valid) {
          loading = true
          const form = {}
          form.userName = loginForm.userName
          form.password = Encrypt(loginForm.password)
          form.info = []
          //   form.loginType = '2'
          //  请求接口地址
          userAccountLogin(form).then(res => {
            // console.log(res)
            // setToken(res.data.token)
            // profile.value.token = res.data.token
            // profile.value.userName = res.data.userName
            store.commit('user/setUser', { userName: res.data.userName, token: res.data.token, info: res.data.info })
            localStorage.setItem('linting-client-pc-store', res.data.token)
            store.dispatch('home/setActive', '1')
            router.push({ path: '/' })
            Message({ type: 'success', text: '登录成功' })
            loading = false
          }).catch((res) => {
            Message({ type: 'error', text: '用户名或密码错误' })
            loading = false
          })
        //   this.$post(this.$api.url.login, form).then((res) => {
        //     if (res.status === 0) {
        //       profile.value.token = res.data.token
        //       sessionStorage.setItem('tokenId', res.data.token)
        //       this.SET_ALL_USER_INFO(res.data)
        //       router.push({ path: '/' })
        //       loading = false
        //     } else {
        //       this.$message.error(res.msg)
        //       loading = false
        //     //   this.freshValidate()
        //     }
        //   }).catch(() => {
        //     this.$message.error('登录出错啦~')
        //     loading = false
        //     // this.freshValidate()
        //   })
        } else {
          console.log('error submit!!')
          loading = false
          return false
        }
      })
    }
    function getOtherQuery (query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
    // function freshValidate () {
    //   this.$fetch(this.$api.url.validateCode).then(res => {
    //     let blob = new Blob([res], { type: 'image/jpeg' })
    //     this.validateimg = window.URL.createObjectURL(blob)
    //     blob = null
    //   }).catch(() => {
    //     this.validateimg = ''
    //     this.$message.error('验证码获取失败，请重新获取！')
    //   })
    // }
    function forgetPassword () {
      // 忘记密码
      this.forgetDialog = true
      // this.$refs.forgetDialog.showDialog = true;
    }
    function getShortMessageCode () {
      // 获取短信验证码
    //   if (!this.verification || this.loadingMessage) {
    //     // 如果正在显示加载中图标或者是倒计时
    //     return
    //   }
    //   verifyCodeLoginFormRef.value.validateField(['userName'], errMsg => {
    //     if (errMsg) {
    //       throw new Error(errMsg)
    //       // return false;
    //     }
    //   })
    //   if (this.timer === 0) {
    //     this.timer = 60
    //   }
    //   this.loadingMessage = true
    //   const toSend = JSON.parse(JSON.stringify({ phone: this.verifyCodeLoginForm.userName }))
    //   this.$postJson(this.$api.url.messageCode, toSend).then((res) => {
    //     // 接口响应后展示开始倒计时
    //     this.verification = false
    //     // 接口响应后关闭遮罩层
    //     this.loadingMessage = false
    //     // eslint-disable-next-line camelcase
    //     const auth_timer = setInterval(() => {
    //       this.timer--
    //       if (this.timer <= 0) {
    //         this.verification = true
    //         clearInterval(auth_timer)
    //       }
    //     }, 1000)
    //     if (res.status === 0) {
    //       this.$message({
    //         message: res.data,
    //         type: 'success'
    //       })
    //     } else {
    //       this.$message.error(res.msg)
    //       // 接口响应失败，清除定时器
    //       clearInterval(auth_timer)
    //       this.timer = 60
    //       this.verification = true
    //     }
    //   }).catch(() => {
    //     this.$message.error('短信验证码获取失败，请稍后重新获取！')
    //     this.loadingMessage = false
    //   })
    }
    function handleMessageLogin () {
      // 注册
      verifyCodeLoginFormRef.value.validate((valid) => {
        console.log(valid)
        if (valid) {
          loading2 = true
          const form = {}
          // 账号
          form.userName = verifyCodeLoginForm.userName
          // 密码
          form.password = Encrypt(verifyCodeLoginForm.messageCode)
          form.info = []
          addUser(form).then(res => {
            console.log(res)
            if (res.code === 500) {
              Message({ type: 'error', text: '账号重复注册' })
            } else {
              Message({ type: 'success', text: '注册成功' })
              location.reload()
              router.go(0)
            }
          }).catch(() => {
            Message({ type: 'error', text: '注册出错啦~' })
            loading = false
          })

          // 登录类型
        //   form.loginType = '1'
        //   this.$post(this.$api.url.login, form).then((res) => {
        //     if (res.status === 0) {
        //       sessionStorage.setItem('tokenId', res.data.token)
        //       this.SET_ALL_USER_INFO(res.data)
        //       router.push({ path: '/contentManage' })
        //       loading2 = false
        //     } else {
        //       this.$message.error(res.msg)
        //       loading2 = false
        //     //   this.freshValidate()
        //     }
        //   }).catch(() => {
        //     this.$message.error('登录出错啦~')
        //     loading2 = false
        //     // this.freshValidate()
        //   })
        // } else {
        //   console.log('submit Error')
        //   loading2 = false
        //   return false
        }
      })
    }
    function closeDialog () {
      this.forgetDialog = false
    }
    // watch(
    //   $route, function (route) {
    //     const query = route.query
    //     if (query) {
    //       this.redirect = query.redirect
    //       this.otherQuery = this.getOtherQuery(query)
    //     }
    //   }, { immediate: true },
    //   loginType, function (val) {
    //   // 切换登录方式时清除一次表单验证
    //     this.$nextTick(() => {
    //       val === 2 ? this.$refs.verifyCodeLoginForm.clearValidate() : this.$refs.loginForm.clearValidate()
    //     })
    //   })
    return {
      loginForm,
      loginFormRef,
      loginRules,
      shortMessageLoginRules,
      passwordType,
      loading,
      loading2,
      profile,
      showDialog,
      redirect,
      otherQuery,
      validateimg,
      loginType,
      verifyCodeLoginForm,
      verifyCodeLoginFormRef,
      verification,
      timer,
      forgetDialog,
      loadingMessage,
      checkCapslock,
      showPwd,
      handleLogin,
      getOtherQuery,
      //   freshValidate,
      forgetPassword,
      getShortMessageCode,
      handleMessageLogin,
      closeDialog
    }
  }
}
</script>

<style lang="less">

@supports (-webkit-mask: none) and (not (cater-color: #fff)) {
  .login-container .el-input input {
    color: #fff;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    // height: 13.33vw;
    width: 85%;
    .el-input__wrapper{
        background-color: #283443;
        border: 0px !important;
        box-shadow: none;
    }
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: #fff;
      height: 47px;
      caret-color: #fff;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #283443 inset !important;
        -webkit-text-fill-color: #fff !important;
      }
    }
  }
  .validatecode{
      .el-input{
          width: 70%;
      }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="less" scoped>
.login-container {
  min-height: 100vh !important;
  width: 100vw !important;
  background-color: #2d3a4b;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 140px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: #889aa4;
    vertical-align: middle;
    font-size: 20px;
    width: 33px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    top: 100px;
    .title {
      font-size: 26px;
      color: #eee;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: #889aa4;
    cursor: pointer;
    user-select: none;
  }
  .show-validate{
      position: absolute;
      right:0;top:5%;
      height:90%;
      width:auto;
      min-width:20%;
      z-index: 10;
      color:#fff;
      img{
          height:100%;
          width:auto;

      }
      .freshbtn{
          position: absolute;
          right:0;top:0;
          height:100%;
          width:100%;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 20px;
          opacity: .3;
      }
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}

.forget{
    display: flex;
    justify-content: center;
    height: 16px;
    opacity: 0.8;
    font-family: MicrosoftYaHei;
    font-size: 12px;
    color: #FFFFFF;
    letter-spacing: 0;
    text-align: center;
    font-weight: 400;
    cursor: pointer;
}
.loginType{
    text-align: center;
    font-family: MicrosoftYaHei;
    font-size: 18px;
    color: #FFFFFF;
    letter-spacing: 0;
    text-align: center;
    font-weight: 400;
    display: flex;
    justify-content: space-between;
    position: relative;
    top: 100px;
    width: 300px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 200;
    >div{
        padding: 0 0 5px 0;
        position: relative;
        cursor: default;
        opacity: 0.6;
    }
}

.loginType {
    >.loginTypeSelected {
         opacity: 1;
    }
}
.loginTypeSelected::after{
    content: "";
    width: 62px;
    height: 2px;
    background: #409EFF;
    border-radius: 2.5px;
    position: absolute;
    top: 30px;
    left: 50%;
    transform: translateX(-50%);
}
.getMessageCode{
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: #409EFF;
    cursor: pointer;
    user-select: none;
    font-weight: 600;
    font-size: 12px;
    font-family: MicrosoftYaHeiSemibold;
    padding-left: 1px
}
.disableClick{
    cursor:not-allowed;
}
</style>
